package per.ethan.springboot.example.util;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import per.ethan.springboot.example.entity.Good;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author Ethan
 * @date 2020/05/30 15:48
 */
public class HtmlParseUtil {

    public static void main(String[] args) {
        HtmlParseUtil.parseJingDong("数据库").forEach(System.out::println);
    }

    public static List<Good> parseJingDong(String keyword) {
        String url = "https://search.jd.com/Search?keyword=" + keyword;

        try {
            Document document = Jsoup.parse(new URL(url), 30000);
            Element element = document.getElementById("J_goodsList");
            Elements elements = element.getElementsByTag("li");

            List<Good> goodList = new ArrayList<>();

            for (Element el : elements) {
                String img = el.getElementsByTag("img").eq(0).attr("src");
                String price = el.getElementsByClass("p-price").eq(0).text();
                String title = el.getElementsByClass("p-name").eq(0).text();

                Good good = new Good(title, img, price);
                goodList.add(good);
            }

            return goodList;
        } catch (IOException e) {
            e.printStackTrace();
        }

        return Collections.emptyList();
    }

}
